package com.ycd.Servlet;

import com.ycd.Entity.UserEntity;
import com.ycd.Service.UserEntityService;
import com.ycd.Service.impl.UserEntityServiceImpl;
import com.ycd.Util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * @Description 登录Servlet
 * @Author ycd
 * @Date : 2022/3/16 16:59
 * @Version : 1.0
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //规范字符集
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        //获取用户传递的参数

        String acct = req.getParameter("userAcct");

        String pwd = req.getParameter("userPwd");
        pwd = MD5Util.toMD5(pwd);
        UserEntityService userEntityService=new UserEntityServiceImpl();
        if (acct != null && pwd != null) {
            UserEntity userentity = userEntityService.getUserByAcct(acct);
            if (userentity == null) {
                //用户名不存在 回到登录界面
                req.getRequestDispatcher("login.h?type=1").forward(req,resp);
            } else {
                if (Objects.equals(pwd, userentity.getPwd())) {
                    //用户登录成功  -页面跳转
                    //登录成功，我们将用户信息保存到session对象
                    HttpSession session = req.getSession();
                    session.setAttribute("user", userentity);
                    //首页界面
                    resp.sendRedirect("index.h");
                } else {
                    //密码错误 登录界面
                    resp.sendRedirect("login.h?type=2");
                }
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
